package logic

import (
	"context"
	"day15/api/pkg"
	"day15/app_config"
	"day15/model/redis"
	"time"

	"day15/api/internal/svc"
	"day15/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSendLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendLogic {
	return &SendLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SendLogic) Send(req *types.SendSmsRequest) (resp *types.ApiResponse, err error) {
	// todo: add your logic here and delete this line
	SmSCountKey := "SMS-COUNT-" + req.Phone
	count, _ := redis.Rdb.Get(SmSCountKey).Int()
	if count >= 3 {
		return &types.ApiResponse{
			Code: 0,
			Msg:  "同一个手机号一天只能发送3次",
			Data: nil,
		}, nil
	}

	client := pkg.NewClient(
		app_config.AppConf.AliYunSms.AccessKey,
		app_config.AppConf.AliYunSms.SecretKey,
		app_config.AppConf.AliYunSms.RegionID,
		app_config.AppConf.AliYunSms.SignName,
		app_config.AppConf.AliYunSms.TemplateCode,
	)
	code := pkg.GenRandCode(6)
	err = client.SendSMS(req.Phone, code)
	if err != nil {
		return &types.ApiResponse{
			Code: 0,
			Msg:  "短信发送失败",
			Data: nil,
		}, nil
	}

	key := "SMS-" + req.From + "-" + req.Phone
	redis.Rdb.Set(key, code, time.Minute*5)

	//redis.Rdb.Incr(SmSCountKey)                 //incr
	//redis.Rdb.Expire(SmSCountKey, time.Hour*24) //设置过期时间

	return &types.ApiResponse{
		Code: 200,
		Msg:  "短信发送成功",
		Data: nil,
	}, nil

}
